package com.itheima.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.aspect.TestAnno;
import com.itheima.Exception.BizException;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpLogService;
import com.itheima.service.EmpService;
import com.itheima.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExprService empExprService;
    @Autowired
    private EmpLogService empLogService;
    @Autowired
    private EmpExprMapper empExprMapper;

    @TestAnno(name = "1")
    @Override
    public PageBean pageEmp(EmpQueryParam param) {
        PageBean pageBean = new PageBean();

        PageHelper.startPage(param.getPage(), param.getPageSize());
        Page<Emp> p = empMapper.pageEmp(param);

        pageBean.setRows(p);
        pageBean.setTotal(p.getTotal());
        return pageBean;
    }

    /**
     * 新增员工
     * @param emp
     */
    @Override
    @Transactional(rollbackFor = Exception.class)//事务处理,新增员工与新增员工经历必须同时添加成功或者失败.
    public void addEmp(Emp emp) {
        try {
            emp.setCreateTime(LocalDateTime.now());
            emp.setUpdateTime(LocalDateTime.now());
            empMapper.insertEmp(emp);
            if(emp.getExprList() != null && emp.getExprList().size()>0){
                emp.getExprList().forEach(expr->{
                    expr.setEmpId(emp.getId());// expr是EmpExpr类型的对象
                });
                empExprService.saveBatch(emp.getExprList());//新增员工之后再调用empExprService新增该员工的工作经历
            }
        } finally {
            EmpLog empLog = new EmpLog();
            empLog.setInfo(emp.toString());
            empLog.setOperateTime(LocalDateTime.now());
            empLogService.insertLog(empLog);
        }
    }

    @Override
    @Transactional
    public void deleteByIds(List<Integer> ids) {
        //删除员工
        empMapper.deleteByIds(ids);

        //删除员工经历
        empExprMapper.deleteByEmpIds(ids);
    }


    /**
     * 回显员工信息
     * @param id
     * @return
     */
    @Override
    public Emp getEmp(Integer id) {
        return empMapper.selectById(id);
    }



    @Override
    @Transactional
    public void updateEmp(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        //修改员工信息
        empMapper.update(emp);
        //删除该员工工作经历
        empExprMapper.deleteByEmpIds(Arrays.asList(emp.getId()));
        //新增该员工工作经历
        Integer empId = emp.getId();
        if(emp.getExprList() != null && emp.getExprList().size()>0){
            emp.getExprList().forEach(expr->{
                expr.setEmpId(emp.getId());// expr是EmpExpr类型的对象
            });
            empExprService.saveBatch(emp.getExprList());//新增员工之后再调用empExprService新增该员工的工作经历
        }
    }


    @Override
    public List<Emp> getEmps() {
        return empMapper.selectEmps();
    }

    /**
     * 登陆验证，使用username从数据库查询结果，结果以Emp类型的对象的形式返回到Service层
     * @param emp
     * @return
     */
    @Override
    public LoginInfo login(Emp emp) {
        LoginInfo loginInfo = new LoginInfo();
        Emp dbEmp =  empMapper.selectByUsername(emp.getUsername());
        if (dbEmp == null){
            throw new BizException("用户不存在");
        }else if (!dbEmp.getPassword().equals(emp.getPassword())){
            throw new BizException("密码错误");
        }else {
            loginInfo.setId(dbEmp.getId());
            loginInfo.setName(dbEmp.getName());
            loginInfo.setUsername(dbEmp.getUsername());
            //生成token
            Map<String,Object> map = new HashMap<>();
            map.put("id",dbEmp.getId());
            map.put("name",dbEmp.getName());
            map.put("username",dbEmp.getUsername());
            String string = JwtUtils.generateJwt(map);//得到token
            loginInfo.setToken(string);
            return loginInfo;
        }
    }
}
